package com.oba.king.sysmanager.initdb;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;

import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.dbcp.BasicDataSource;

import com.oba.base.util.Util;

public class InitDB {
	
	public void test() {
		HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
		String path = request.getRealPath("");
		System.out.println(path);
		BasicDataSource bds = (BasicDataSource) Util.getBean("dataSource");
		System.out.println(bds.getUrl());
		System.out.println(bds.getUsername());
		System.out.println(bds.getPassword());
		try {
			File file = new File(path+"\\WEB-INF\\classes\\king.sql");
			FileInputStream fis = new FileInputStream(file);
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(bds.getUrl(),bds.getUsername(),bds.getPassword());
			Statement stmt = con.createStatement();
			InputStreamReader isr = new InputStreamReader(fis);
			BufferedReader br = new BufferedReader(isr);
			StringBuffer sb = new StringBuffer();
			String line;
			while((line = br.readLine())!=null) {
				int len = line.length();
				if(len<=0) {
					continue;
				}
				String temp = line.substring(0,1);
				if(!("/".equals(temp)||"#".equals(temp)||"锘".equals(temp))) {
					//sb.append(new String(line.getBytes(),"UTF-8"));
					sb.append(line);
					System.out.println("---"+sb);
					if(";".equals(line.substring(len-1))) {
						System.out.println(sb.toString());
						stmt.execute(sb.toString());
						sb.setLength(0);
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
